package barcelonaEventsWS.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import barcelonaEventsWS.data.EventDTO;

public class BarcelonaEventsWSDAO implements IBarcelonaEventsWSDAO
{
	private Connection connection = null;

	@Override
	public void connect() throws SQLException, ClassNotFoundException
	{
		Class.forName("org.sqlite.JDBC");
		connection = java.sql.DriverManager.getConnection("jdbc:sqlite:/home/ander/workspace/ISOProject/WebServices/BarcelonaEventsWS/db/BarcelonaEventsWS.db"); //TODO FEDE
		
		System.out.println ("Base de datos: nueva conexión."); // registro
	}

	@Override
	public void disconnect() throws SQLException
	{
		checkConnected();
		connection.close();
		System.out.println ("Base de datos: conexión cerrada."); // registro
	}
	
	private void checkConnected()
	{
		if (connection == null)
			throw new IllegalStateException("A�n no se ha creado la conexi�n a la base de datos");
	}

	public Statement createStatement() throws SQLException
	{
		checkConnected();
		return connection.createStatement();
	}

	@Override
	public EventDTO[] getEvents()
	{
		EventDTO[] arrayEventDTO = null;
		
		try
		{
			connect();
			
			Statement sentencia = createStatement();
			
			String query = "SELECT COUNT(*) FROM events";
			ResultSet rs = sentencia.executeQuery(query);
			arrayEventDTO = new EventDTO[rs.getInt(1)];
			
			sentencia = createStatement();
			query = "SELECT * FROM events";
			rs = sentencia.executeQuery(query);
			
			int i = 0;
			
			while(rs.next())
			{
//				System.out.println("EventDO = " + rs.getString("Name") + " " + rs.getString("Date") + " " + rs.getString("Description") + " " + rs.getInt("Places"));
				
				arrayEventDTO[i] = new EventDTO(rs.getString("Name"), rs.getString("Date"), rs.getString("Description"), rs.getInt("Places"));
				i++;
			}
			
			disconnect();
		} 
		catch (SQLException e)
		{
			System.err.println("SQLException exception: " + e.getMessage());
			e.printStackTrace();
		} 
		catch (ClassNotFoundException e)
		{
			System.err.println("ClassNotFoundException exception: " + e.getMessage());
			e.printStackTrace();
		}

		return arrayEventDTO;
	}
}
